package com.jzo2o.orders.manager.listener;

import com.alibaba.fastjson.JSON;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.model.msg.TradeStatusMsg;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 监听mq消息，接收支付结果
 *
 * @author itcast
 **/
@Slf4j
@Component
public class TradeStatusListener {
    @Resource
    private IOrdersCreateService ordersCreateService;

    /**
     * 更新支付结果
     * 支付成功
     *
     * @param msg 消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS),
            exchange = @Exchange(name = MqConstants.Exchanges.TRADE, type = ExchangeTypes.TOPIC),
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS
    ))
    public void listenTradeUpdatePayStatusMsg(String msg) {
        log.info("消费者接收更新支付结果消息成功: 参数为: {}", msg);
        // 将消息转换成原本的类型
        List<TradeStatusMsg> tradeStatusMsg
                = JSON.parseArray(msg, TradeStatusMsg.class);
        // 将数据进行筛选
        List<TradeStatusMsg> collect = tradeStatusMsg.stream()
                .filter(item -> item.getStatusCode() == 4 && "jzo2o.orders".equals(item.getProductAppId()))
                .collect(Collectors.toList());
        // 筛选出的数据为空直接结束
        if(ObjectUtils.isNull(collect)) return;
        // 不为空则对订单信息进行更新
        collect.forEach(item -> ordersCreateService.updateOrderInfo(item));
    }
}